#!/usr/bin/python
import os
import sys
import shutil
import zipfile


szPrompt = "Version number: "
szCopyDir = "Civcraft SC"
szBaseRarFile = ".BaseRarFile.rar"

szVersion = raw_input(szPrompt)
szRarFile = "CivcraftSC-v%s.rar" % szVersion

# Test if file is open
if os.path.isfile(os.path.join(szRarFile)):
    print ""
    print "ERROR: File already exists.... exiting."
    raw_input()
    sys.exit()

os.mkdir(szCopyDir)
    
# Walk through directory adding files to the new directory.

for root, dirs, files in os.walk(os.path.join("..", szCopyDir)):
    if ".svn" in dirs:
        dirs.remove(".svn")

    for directory in dirs:
        fullDirName = os.path.join(root, directory)
        os.mkdir(os.path.join(szCopyDir[3:], fullDirName))

    for filename in files:
        print "'%s', '%s'" % (root, filename)
        fullFilename = os.path.join(root, filename)
        shutil.copyfile(fullFilename, os.path.join(root[3:], filename))

originalDir = 'C:\\cygwin\\home\\Gerikes\\civ4-civcraft\\trunk\\SDK Source\\CvGameCoreDLL_v161\\CvGameCoreDLL'
newDir = 'Y:\\originalSDK_debug\\CvGameCoreDLL_v161\\CvGameCoreDLL'
diffFile = "diff.txt"
szCommand = 'diff -X ignorepatterns.txt "%s" "%s" > %s' % (originalDir, newDir, diffFile)


print "Creating diff...."
os.system(szCommand)

diffFile = open("diff.txt", "r")

szSDKRarFile = "CivcraftSC-SDKChanges-v%s.rar" % szVersion

sourceDir = os.path.join("..", "SDK Source", "CvGameCoreDLL_v161", "CvGameCoreDLL")

szSDKChangeDir = "CvGameCoreDLL"
os.makedirs(szSDKChangeDir)


for line in diffFile.readlines():
    if line.startswith("diff") or line.startswith("Only in"):
        name = line.split(" ")[-1]
        if name.find("/") != -1:
            name = name.split("/")[-1]
        name = name.strip()
        shutil.copyfile(os.path.join(sourceDir, name), os.path.join(szSDKChangeDir, name))

diffFile.close()

shutil.move("diff.txt", os.path.join(szSDKChangeDir, "diff.txt"))

# Use rar to add the files to the rars
print "Adding SDK Source to rar archives..."
os.system('rar a "%s" "%s"' % (szSDKRarFile, szSDKChangeDir))
print "Adding Mod Folder to rar archives..."
os.system('rar a "%s" "%s"' % (szRarFile, szCopyDir))

print "Deleting SDK Source Folder..."
shutil.rmtree(szSDKChangeDir)
print "Deleting Mod Folder..."
shutil.rmtree(szCopyDir)


# Print end message
print ""
print "Creation complete."
raw_input()


    
